package com.xrit.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.xrit.constant.MessageConstant;
import com.xrit.exception.CustomException;
import com.xrit.mapper.MemberMapper;
import com.xrit.mapper.OrderMapper;
import com.xrit.mapper.OrderSettingMapper;
import com.xrit.pojo.*;
import com.xrit.result.Result;
import com.xrit.service.OrderService;
import com.xrit.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderSettingMapper orderSettingMapper;

    @Autowired
    private MemberMapper memberMapper;

    @Override
    public Map<String,Object> findById(Integer id) {
        return orderMapper.findOrderDetailById(id);
    }

    @Transactional
    @Override
    public Result doOrder(Map<String, String> map) throws CustomException {
        String orderDate = map.get("orderDate");
        String telephone = map.get("telephone");
        String orderType = map.get("orderType");
        Integer setmealId = Integer.parseInt(map.get("setmealId"));//准备套餐id
        //测试数据
//        Order order = new Order();
//        order.setId(17);
        //a.预约设置辅助类
        OrderSettingExample ose=new OrderSettingExample();
        OrderSettingExample.Criteria osec = ose.createCriteria();
//        1、检查用户所选择的预约日期**是否已经有预约设置**，如果没有设置则无法进行预约
        try {
            osec.andOrderdateEqualTo(DateUtils.parseString2Date(orderDate));
            List<OrderSetting> list = orderSettingMapper.selectByExample(ose);
            if (list==null || list.size()==0){
                return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);//无效的预约时间
            }
//        2、检查用户所选择的预约日期**是否已经约满**，如果已经约满则无法预约
            OrderSetting orderSetting = list.get(0);
            Integer number = orderSetting.getNumber();
            Integer reservations = orderSetting.getReservations();
            if (number!=null && reservations!=null && number==reservations){
                return new Result(false, MessageConstant.ORDER_FULL);//预约已满
            }
//        3、检查当前用户**是否为会员**，如果是会员则直接完成预约，如果不是会员则自动完成注册并进行预约
            //b.会员辅助类
            MemberExample me=new MemberExample();
            MemberExample.Criteria mec = me.createCriteria();
            mec.andPhonenumberEqualTo(telephone);
            List<Member> members = memberMapper.selectByExample(me);
            Member member=null;
            if (members!=null && members.size()>0){
                //是会员，继续判断是否重复预约
//		  4、检查用户**是否重复预约**（同一个用户在同一天预约了同一个套餐），如果是重复预约则无法完成再次预约
                member = members.get(0);
                //c.预约辅助类
                OrderExample oe=new OrderExample();
                OrderExample.Criteria oec = oe.createCriteria();
                oec.andMemberIdEqualTo(member.getId());//准备会员id
                oec.andOrderdateEqualTo(DateUtils.parseString2Date(orderDate));//准备预约日期
                oec.andSetmealIdEqualTo(setmealId);

                List<Order> orders = orderMapper.selectByExample(oe);
                if (orders!=null && orders.size()>0){
                    return new Result(false, MessageConstant.HAS_ORDERED);//重复预约
                }
                //如果是会员并且无重复预约则直接完成预约
            }else{
                //不是会员，完成第4个，如果不是会员则自动完成注册并进行预约
                //准备会员信息
                member=new Member();
                member.setName(map.get("name"));
                member.setPhonenumber(telephone);
                member.setIdcard(map.get("idCard"));
                member.setSex(map.get("sex"));
                member.setRegtime(new Date());
                memberMapper.insertSelective(member);//完成会员注册
            }
//        5、预约成功，更新当日的已预约人数（走到这一步，说明）
            //5.1 保存预约信息
            Order order=new Order();
            order.setMemberId(member.getId());
            order.setOrderdate(DateUtils.parseString2Date(orderDate));
            order.setOrdertype(orderType);
            order.setOrderstatus(Order.ORDERSTATUS_NO);
            order.setSetmealId(setmealId);
            orderMapper.insertSelective(order);
            //5.2 更新预约人数
            orderSetting.setReservations(orderSetting.getReservations()==null?1:orderSetting.getReservations()+1);
            orderSettingMapper.updateByPrimaryKeySelective(orderSetting);
            return new Result(true, MessageConstant.ORDER_SUCCESS,order);//预约成功
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false, MessageConstant.ORDER_FAIL);//预约失败
    }
}

